package com.cs.aspect;

import com.cs.annotation.AutoAnnouncement;
import com.cs.context.BaseContext;
import com.cs.domain.Announcement;
import com.cs.domain.StudentCourse;
import com.cs.domain.User;
import com.cs.enumeration.OperationType;
import com.cs.mapper.IAnnouncementMapper;
import com.cs.mapper.ICourseMapper;
import com.cs.mapper.IUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义切面，实现自动通知
 */
@Aspect
@Slf4j
@Component
public class AutoAnnounceAspect {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IAnnouncementMapper announcementMapper;

    @Autowired
    private ICourseMapper courseMapper;

    /**
     * 切入点，对哪些类的哪些方法进行拦截
     */
    @Pointcut("execution(* com.cs.service.impl.*.*(..)) && @annotation(com.cs.annotation.AutoAnnouncement)")
    public void AutoAnnoPointCut() {
    }

    /**
     * 后置返回通知，通知中进行自动向用户发送选课通知
     */
    @AfterReturning(pointcut = "AutoAnnoPointCut()", returning = "res")
    public void autoFill(JoinPoint joinPoint, Object res) {
        log.info("开始进行选课自动发送通知...");
        //1.获取业务操作类型
        //1-1 方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //1-2获取注解对象,操作类型
        AutoAnnouncement announcement = signature.getMethod().getAnnotation(AutoAnnouncement.class);
        OperationType type = announcement.value();

        //2.获取方法参数--选课实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            //没有参数，直接返回
            return;
        }
        Object entity = args[0];
        Integer courseId = (Integer) entity;

        //3.根据选课信息发送通知
        if (type == OperationType.CHOOSE) {
            // 查询选课人的用户名
            User user = userMapper.selectById(BaseContext.getCurrentId());
            String userName = user.getUsername();
            // 查询课程名称
            // 根据courseId 查询课程名称
            // 调用courseMapper.selectById(courseId)方法，获取课程名称
            String courseName = courseMapper.selectById(courseId).getCourseName();

            // 拼接信息
            String message = userName + "，您已成功选择课程：" + courseName;
            log.info("信息:{}", message);

            // 将消息写入数据库
            Announcement announcement1 = new Announcement();
            announcement1.setContent(message);
            announcement1.setCreateTime(LocalDateTime.now());
            announcement1.setUserId(BaseContext.getCurrentId());
            announcementMapper.insert(announcement1);
        }
    }
}
